<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="视频名称" prop="videoName">
        <el-input v-model="formData.videoName" placeholder="请输入视频名称" />
      </el-form-item>
      <el-form-item label="上传视频" prop="videoUrl">
        <el-upload
          class="avatar-uploader"
          action=""
          list-type="picture-card"
          v-model:file-list="upload.videoList"
          :limit="1"
          :auto-upload="false"
          :show-file-list="true"
          accept="video/mp4"
          :on-change="handleVideoUplad"
          :on-remove="handleFileRemove"
          :on-exceed="handleExceed"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="上传封面" prop="videoCoverUrl">
        <el-upload
          class="avatar-uploader"
          v-model:file-list="upload.coverList"
          action=""
          list-type="picture-card"
          :limit="1"
          accept="image/*"
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handlePicUplad"
          :on-remove="handleFileRemove"
          :on-exceed="handleExceed"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as VideoApi from '@/mock/official-website/video'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 上传
const upload = ref({
  video: undefined,
  videoList: [],
  cover: undefined,
  coverList: []
})

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  videoName: undefined,
  videoUrl: undefined,
  videoCoverUrl: undefined
})
const formRules = reactive({
  videoName: [{ required: true, message: '视频名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      let res = await VideoApi.getVideo(id)
      console.log(res)
      // 设置上传回显
      upload.value.videoList = [
        {
          name: res.data.videoName,
          url: res.data.videoUrl
        }
      ]
      upload.value.coverList = [
        {
          name: res.data.videoName,
          url: res.data.videoCoverUrl
        }
      ]
      formData.value = res.data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (!upload.value.video || !upload.value.cover) {
    ElMessage.error('请上传视频和封面')
  }
  // 提交请求
  formLoading.value = true
  try {
    // 上传视频和封面
    const videoUrl = await VideoApi.uploadFile({ file: upload.value.video, type: 'file' })
    const videoCoverUrl = await VideoApi.uploadFile({ file: upload.value.cover, type: 'image' })
    // 拿到url给表单赋值，提交表单
    formData.value.videoUrl = videoUrl.url
    formData.value.videoCoverUrl = videoCoverUrl.url
    const data = formData.value as unknown as VideoApi.VideoVO
    if (formType.value === 'create') {
      await VideoApi.createVideo(data)
      message.success(t('common.createSuccess'))
    } else {
      await VideoApi.updateVideo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    videoName: undefined,
    videoUrl: undefined,
    videoCoverUrl: undefined
  }
  formRef.value?.resetFields()
}

// 限制文件上传大小
const deterFileSize = (rawFile, size) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件最大不能超过 2MB!')
    return false
  }
  return true
}

// 视频文件上传
const handleVideoUplad = (file, fileList) => {
  if (deterFileSize(file, 15)) {
    upload.value.file = file
  }
}

// 图片文件上传
const handlePicUplad = (file, fileList) => {
  if (deterFileSize(file, 2)) {
    upload.value.image = file
  }
}

// // 文件移除
const handleFileRemove = async (file) => {
  if (file && file.status == 'success') {
    await VideoApi.deleteUploadFile(file.url)
  }
  ElMessage.success('删除成功')
}
// 文件超出个数限制
const handleExceed = () => {
  ElMessage.warning('超出文件个数限制')
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
